package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.jwts.JwtUtil;
import com.atguigu.lease.common.redis.RedisConstant;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import kotlin.jvm.internal.Lambda;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SystemUserService systemUserService;

    /**
     * 逻辑：获取验证码和验证码的key（admin:login:uuid）,封装进CaptchaVo并返回
     * 验证码存储在redis,
     * 类型string,key：admin:login:uuid，
     * @return
     */
    @Override
    public CaptchaVo getCaptcha() {
        //获取验证码对象
        SpecCaptcha specCaptcha=new SpecCaptcha(130, 48,4);
        //验证码内容：数字|字母
        specCaptcha.setCharType(SpecCaptcha.TYPE_DEFAULT);
        //验证码图片-》base64字符串
        String imageStr = specCaptcha.toBase64();
        //正确的验证码
        String text = specCaptcha.text();
        //验证码key值
        String key= RedisConstant.ADMIN_LOGIN_PREFIX+ UUID.randomUUID().toString().replace("-","");
        //redis中存储验证码，
        redisTemplate.opsForValue().set(key,text,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        //封装key,验证码图片
        CaptchaVo captchaVo = new CaptchaVo(imageStr, key);
        return captchaVo;
    }

    /**
     * 根据用户名密码验证码uuid,登录，
     * 开始验证：
     *      验证验证码是否过期
     *      验证码是否正确
     *      验证用户名，密码，是否禁用
     *  验证通过：
     *      根据用户id，用户名生成token,并返回
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {
        String redisCode = (String)redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        //验证验证码是否过期
        if(ObjectUtils.isEmpty(redisCode)){
            //如验证码过期，
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //验证码是否正确
        if(!redisCode.equalsIgnoreCase(loginVo.getCaptchaCode())){
            //验证码不正确
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //获取用户
        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(systemUserLambdaQueryWrapper);
        //验证用户名
        if(ObjectUtils.isEmpty(systemUser)){
            //用户名错误
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //判定密码
        //密码执行MD5加密处理，再和真实密码对比
        if(!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            //密码错误
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //判定是否被禁用
        if(systemUser.getStatus().getCode()== BaseStatus.DISABLE.getCode()){
            //被禁用
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //生成token
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());

        return token;
    }
}
